package server;

import java.io.*;
import java.lang.reflect.Method;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.regex.Matcher;

/**
 * @author xsl
 * @date 2021/2/20 22:46
 * @Description: MyClassLoader
 */
public class MyClassLoader extends ClassLoader {


  private String path;
  public MyClassLoader(String path){
      this.path = path;
  }
    @Override
    public Class findClass(String name){
        byte[] b = loaderClassData(name);
        return defineClass(name, b, 0, b.length);
    }
    private byte[] loaderClassData(String name){
        name = path + name.replaceAll("\\.",  Matcher.quoteReplacement(File.separator)) + ".class";
        InputStream in = null;
        ByteArrayOutputStream out = null;
        try{
            in = new FileInputStream(new File(name));
            out = new ByteArrayOutputStream();
            int i = 0;
            while((i = in.read()) != -1){
                out.write(i);
            }
            return out.toByteArray();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try {
                out.close();
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
